package com.example.seven.mynews.data;

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by seven on 16-7-3.
 *
 */
public class MyDB {

    class MySQLiteOpenHelper extends SQLiteOpenHelper{

        public MySQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
            // TODO 自动生成的构造函数存根
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO 自动生成的方法存根
            db.execSQL("create table user (_id integer primary key autoincrement,"+
                    "username varchar(20),password varchar(20),headeimageid String)");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO 自动生成的方法存根

        }


    }

    private Context context;
    private String name;
    private SQLiteDatabase aSqLiteDatabase;

    public MyDB(Context context, String name) {
        super();
        this.context = context;
        this.name = name;
    }

    public void open() {
        //打开数据库
        MySQLiteOpenHelper aMySQLiteOpenHelper = new MySQLiteOpenHelper(context, name, null, 1);
        aSqLiteDatabase = aMySQLiteOpenHelper.getWritableDatabase();//获取写入权限

    }

    public void close() {
        if (aSqLiteDatabase!=null) {
            aSqLiteDatabase.close();
        }

    }

    public void insert(Users aUser) {
        aSqLiteDatabase.execSQL("insert into user values(null,?,?,?)",
                new Object[]{aUser.getUserName(),aUser.getPassword(),aUser.getHeadImageId()});
    }

    public Cursor queryAll() {
        return aSqLiteDatabase.rawQuery("select * from user", null);
    }

    public Cursor queryById(int id) {
        return aSqLiteDatabase.rawQuery("select * from user where _id="+id, null);
    }

    public void deleteById(int id) {
        aSqLiteDatabase.execSQL("delete from user where _id=?", new Object[]{id});
    }

    public void updateById(int id,Users aUsers) {
        aSqLiteDatabase.execSQL("update user set username=?,password=?,headeimageid=? where _id=?",
                new Object[]{aUsers.getUserName(),aUsers.getPassword(),aUsers.getHeadImageId(),id});
    }


    public boolean login(String username,String password){
        boolean blean = false;
        Cursor cursor = aSqLiteDatabase.rawQuery("select * from user where username = ? and password = ?", new String[]{username, password});
        if (cursor.moveToFirst() == true){
            blean = true;
            cursor.close();
        }
        return blean;
    }
}
